package com.base.myproject.server;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;

import com.base.myproject.server.database.PoolMan;
import com.google.gwt.core.client.GWT;

public class BaseFileUploadServlet extends HttpServlet{
	private ServletConfig config;
	
	protected void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		//response.setContentType("multipart/form-data;charset=UTF-8");
		//PrintWriter out = response.getWriter();
		//request.setCharacterEncoding("utf-8");
		
		 boolean isMultipart = ServletFileUpload.isMultipartContent(request);  
//		 System.out.println(config.getServletContext().getRealPath("/"));
//		 System.out.println(config.getServletContext().getContextPath());
//		 System.out.println(config.getServletContext().getServerInfo());
		 GWT.log("is multipart? " + Boolean.toString(isMultipart), null);  
		 FileItemFactory factory = new DiskFileItemFactory();

		 ServletFileUpload upload = new ServletFileUpload(factory);  
		 Enumeration  enumeration=request.getParameterNames();
			System.out.println("size=------++@---");
			while(enumeration.hasMoreElements())
			{
				String  eeee =""+ enumeration.nextElement();
				System.out.print("e="+eeee+"=");
				System.out.println(request.getParameter(""+eeee));
			}
			
			String  table  = request.getParameter("table");
			String  key  = request.getParameter("key");
			String  keyvalue  = request.getParameter("keyvalue");
			String  idx= request.getParameter("idx");
			
			String uuid =request.getParameter("system_uuid"); 
			String  bcode  =UserPool.getInstance().getUser(uuid).getBcode();
		 try {
			FileItemIterator iter = upload.getItemIterator(request);
			while (iter.hasNext()) {  
				 FileItemStream item = iter.next();  
	                String name = item.getFieldName();  
	                
	                InputStream stream = item.openStream();  
	                
	                if (item.isFormField()) {  
	                    System.out.println("Form field " + name + " with value "  
	                            + Streams.asString(stream) + " detected.");  
	                } else {  
	                	 System.out.println("File field " + name  
	                             + " with file name " + item.getName()  
	                             + " detected.");  
	                	 String filepath= createfilepath();
		                //	createfile(item.getName(), filepath);
	                	 BufferedInputStream inputStream = new BufferedInputStream(  
	                             stream);
	                	 File f = createfile(item.getName(), filepath);
	                	 BufferedOutputStream outputStream = new BufferedOutputStream(  
	                             new FileOutputStream(f));
	                	
	                	
	                	 Streams.copy(inputStream, outputStream, true);
	                	 String warpath = config.getServletContext().getRealPath("/");
	                	String imagepath =  f.getPath().substring(warpath.length());
	                	 try {
						//	saveUpdateload("ccodeimages","ccode","1001","idx","1001","imagepath",imagepath);
	                		 saveUpdateload(table,key,keyvalue,idx,bcode,"imagepath",imagepath);
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
	                }
	                stream.close();  
			}
			 GWT.log("上传成功!",null);  
		//	 out.println("success");
		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  
	}
	
    public void init(ServletConfig config) throws ServletException {
        this.config = config;
    }


	
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}
	/**
	 * 设置路径，在war目录下创建busiiamgs的文件夹
	 * @return
	 */
	public  String  createfilepath()
	{
		String filepath=config.getServletContext().getRealPath("/");
		
		java.text.SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		 String a1=sdf.format(new Date());
		 filepath =filepath+"busiimages"+File.separatorChar+a1+File.separatorChar;
		 GWT.log(filepath,null);
		return filepath;
	}
	/**
	 * 根据文件名，指定路径，创建一个文件
	 * @param file
	 * @param filepath
	 * @return
	 * @throws IOException
	 */
	
	
	
	public File createfile(String file,String filepath) throws IOException
	{
		File fpath =  new File(filepath);
		if(!fpath.exists())
		fpath.mkdir();

		 File f=new File(file);  
		 String fname =f.getName();
		 
		 java.lang.System.currentTimeMillis();
		    while(f.exists())
	        {
	          
	             if(f.isFile())
	            {
	                f = new File(fpath+File.separator+java.lang.System.currentTimeMillis()+""+fname);
	            }
	         
	        }
	       if(!f.exists())
	       {

	        f.createNewFile();
	       }
	       GWT.log(f.getPath(),null);
	       return f;
	
	}
	/**
	 * 
	 * @param table 表名
	 * @param key 主键名称
	 * @param keyvalue 主键值
	 * @param idxname 索引名称
	 * @param bcode 人员码
	 * @param imagespathcolumnname 图片储存数据库的路径字段名称
	 * @param filename 图片储存数据库的路径
	 * @throws Exception
	 */
	public void saveUpdateload(String table,String key,String keyvalue,String idxname,String bcode,String imagespathcolumnname,String filename) throws Exception
	{
		PoolMan pm = new PoolMan();
		String autoincsql = "select isnull(max(substring("+idxname+",CHARINDEX('_',"+idxname+")+1,len("+idxname+"))),0) as inc from "+table+" where "+idxname+" like '"+bcode+"_%'";
		System.out.println(autoincsql);
		ResultSet rs = pm.executeQuery(autoincsql);
		rs.next();
	
		int inc = rs.getInt("inc")+1;
		String idxvalue = bcode+"_"+inc;
		String insertsql = "insert into "+table+"("+key+","+idxname+",bcode,"+imagespathcolumnname+") values('"+keyvalue+"','"+idxvalue+"','"+bcode+"','"+filename+"')";
		pm.Update(insertsql);
		
	}
	public static void main(String[] argv) throws IOException
	{
		 File f=new File("d:/temp/aa.tif");  
		 String fname =f.getName();
		 java.lang.System.currentTimeMillis();
		    while(f.exists())
	        {
	          
	             if(f.isFile())
	            {
	                f = new File(f.getParent()+File.separator+java.lang.System.currentTimeMillis()+""+fname);
	            }
	         
	        }
	       if(!f.exists())
	       {

	        f.createNewFile();
	       }
	}
	
	
}
